<template>
  <div class="map-container">
    <div id="map" ref="mapContainer"></div>
    <div class="map-controls">
      <div class="map-type-selector">
        <h4>地图类型</h4>
        <div class="map-type-buttons">
          <button 
            v-for="(name, type) in mapTypes" 
            :key="type"
            @click="changeMapType(Number(type))"
            :class="['map-type-btn', { active: selectedMapType === Number(type) }]"
          >
            {{ name }}
          </button>
        </div>
      </div>
      <div class="mouse-info">
        <div>纬度: {{ mouseInfo.lat.toFixed(4) }}</div>
        <div>经度: {{ mouseInfo.lng.toFixed(4) }}</div>
        <div>缩放: {{ mouseInfo.zoom }}</div>
      </div>
      <button @click="addRandomPoint" class="control-btn">添加随机点</button>
      <button @click="clearAllPoints" class="control-btn">清除所有点</button>
      <div class="legend">
        <h4>图例</h4>
        <div class="legend-item" v-for="(color, type) in pointColors" :key="type">
          <span class="legend-color" :style="{ backgroundColor: color }"></span>
          <span>{{ type }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'

// 修复 Leaflet 默认图标路径问题
delete (L.Icon.Default.prototype as any)._getIconUrl
L.Icon.Default.mergeOptions({
  iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon-2x.png',
  iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png',
})

interface MapPoint {
  id: string
  lat: number
  lng: number
  type: string
  color: string
  marker: L.Marker
}

const mapContainer = ref<HTMLElement>()
const map = ref<L.Map>()
const tileLayer = ref<L.TileLayer>()
const points = ref<MapPoint[]>([])

// 地图类型配置
const selectedMapType = ref(3)
const mapTypes = {
  1: '卫星图',
  2: '天地图',
  3: '高德地图'
}

// 鼠标信息
const mouseInfo = reactive({
  lat: 0,
  lng: 0,
  zoom: 13
})

// 定义不同类型的点颜色
const pointColors = {
  '餐厅': '#ff4757',
  '商店': '#2ed573',
  '医院': '#3742fa',
  '学校': '#ffa502',
  '公园': '#2f3542'
}

const pointTypes = Object.keys(pointColors)

// 获取地图URL
const getMapUrl = (type: number) => {
  switch (type) {
    case 1:
      return "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
    case 2:
      return "http://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=f13dfbef9ecb8e6493830a5793cc4531"
    case 3:
      return "https://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}"
    default:
      return "https://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}"
  }
}

// 获取地图配置
const getMapConfig = (type: number) => {
  switch (type) {
    case 1:
      return {
        url: getMapUrl(type),
        attribution: '© Esri'
      }
    case 2:
      return {
        url: getMapUrl(type),
        attribution: '© 天地图'
      }
    case 3:
      return {
        url: getMapUrl(type),
        attribution: '© 高德地图'
      }
    default:
      return {
        url: getMapUrl(type),
        attribution: '© 高德地图'
      }
  }
}

// 切换地图类型
const changeMapType = (type: number) => {
  selectedMapType.value = type
  if (map.value) {
    // 移除当前图层
    if (tileLayer.value) {
      map.value.removeLayer(tileLayer.value)
    }
    
    // 添加新图层
    const config = getMapConfig(type)
    tileLayer.value = L.tileLayer(config.url, {
      attribution: config.attribution
    }).addTo(map.value)
  }
}

// 初始化地图
const initMap = (type: number = 3) => {
  if (!mapContainer.value) return

  map.value = L.map(mapContainer.value).setView([34.3416, 108.9398], 13) // 西安坐标

  // 添加地图图层
  const config = getMapConfig(type)
  tileLayer.value = L.tileLayer(config.url, {
    attribution: config.attribution
  }).addTo(map.value)

  // 添加鼠标移动事件监听
  map.value.on('mousemove', (e) => {
    mouseInfo.lat = e.latlng.lat
    mouseInfo.lng = e.latlng.lng
    mouseInfo.zoom = map.value?.getZoom() || 13
  })

  // 添加缩放事件监听
  map.value.on('zoomend', () => {
    mouseInfo.zoom = map.value?.getZoom() || 13
  })

  // 添加一些初始点
  addInitialPoints()
}

// 添加初始点
const addInitialPoints = () => {
  const initialPoints = [
    { lat: 34.3416, lng: 108.9398, type: '餐厅' }, // 西安市中心 钟楼
    { lat: 34.3516, lng: 108.9498, type: '商店' }, // 西安北部
    { lat: 34.3316, lng: 108.9298, type: '医院' }, // 西安南部
    { lat: 34.3616, lng: 108.9598, type: '学校' }, // 西安东北部
    { lat: 34.3216, lng: 108.9198, type: '公园' }  // 西安西南部
  ]

  initialPoints.forEach(point => {
    addPoint(point.lat, point.lng, point.type)
  })
}

// 添加点
const addPoint = (lat: number, lng: number, type: string) => {
  if (!map.value) return

  const color = pointColors[type as keyof typeof pointColors] || '#ff4757'
  const id = `point-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`

  // 创建自定义图标
  const customIcon = L.divIcon({
    className: 'custom-marker',
    html: `<div style="
      width: 20px; 
      height: 20px; 
      background-color: ${color}; 
      border: 2px solid white; 
      border-radius: 50%; 
      box-shadow: 0 2px 4px rgba(0,0,0,0.3);
      animation: pulse 2s infinite;
    "></div>`,
    iconSize: [20, 20],
    iconAnchor: [10, 10]
  })

  // 创建标记
  const marker = L.marker([lat, lng], { icon: customIcon })
    .addTo(map.value)
    .bindPopup(`<b>${type}</b><br>坐标: ${lat.toFixed(4)}, ${lng.toFixed(4)}`)

  // 添加动画效果
  marker.on('add', () => {
    // 标记添加时的动画
    setTimeout(() => {
      marker.getElement()?.style.setProperty('animation', 'bounce 0.6s ease-in-out')
    }, 100)
  })

  // 保存点信息
  const point: MapPoint = {
    id,
    lat,
    lng,
    type,
    color,
    marker
  }

  points.value.push(point)
}

// 添加随机点
const addRandomPoint = () => {
  if (!map.value) return

  const bounds = map.value.getBounds()
  const lat = bounds.getSouth() + Math.random() * (bounds.getNorth() - bounds.getSouth())
  const lng = bounds.getWest() + Math.random() * (bounds.getEast() - bounds.getWest())
  const type = pointTypes[Math.floor(Math.random() * pointTypes.length)]

  addPoint(lat, lng, type)
}

// 清除所有点
const clearAllPoints = () => {
  points.value.forEach(point => {
    point.marker.remove()
  })
  points.value = []
}

// 组件挂载时初始化地图
onMounted(() => {
  initMap(selectedMapType.value)
})

// 组件卸载时清理地图
onUnmounted(() => {
  if (map.value) {
    map.value.remove()
  }
})
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100vw;
  height: 100vh;
}

#map {
  width: 100%;
  height: 100%;
  z-index: 1;
}

.map-controls {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1000;
  background: rgba(255, 255, 255, 0.95);
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.15);
  min-width: 250px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.map-type-selector {
  margin-bottom: 20px;
}

.map-type-selector h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.map-type-buttons {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.map-type-btn {
  padding: 8px 12px;
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 12px;
  color: #495057;
}

.map-type-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

.map-type-btn.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.mouse-info {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 15px;
  font-size: 12px;
  color: #495057;
  border: 1px solid #dee2e6;
}

.mouse-info div {
  margin-bottom: 4px;
}

.mouse-info div:last-child {
  margin-bottom: 0;
}

.control-btn {
  display: block;
  width: 100%;
  margin-bottom: 12px;
  padding: 10px 16px;
  background: linear-gradient(135deg, #007bff, #0056b3);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  font-size: 14px;
}

.control-btn:hover {
  background: linear-gradient(135deg, #0056b3, #004085);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
}

.control-btn:active {
  transform: translateY(0);
}

.legend {
  margin-top: 20px;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
  padding-top: 15px;
}

.legend h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 13px;
  color: #555;
}

.legend-color {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  margin-right: 10px;
  border: 2px solid rgba(255, 255, 255, 0.8);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 动画样式 */
@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.2);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}

/* 确保 Leaflet 样式正确加载 */
:deep(.leaflet-container) {
  font-family: inherit;
}

:deep(.custom-marker) {
  background: transparent;
  border: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .map-controls {
    top: 10px;
    right: 10px;
    left: 10px;
    min-width: auto;
    padding: 15px;
  }
  
  .map-type-buttons {
    grid-template-columns: 1fr;
  }
  
  .control-btn {
    padding: 8px 12px;
    font-size: 13px;
  }
  
  .legend h4 {
    font-size: 14px;
  }
  
  .legend-item {
    font-size: 12px;
  }
}
</style> 